using UnityEngine;
using UnityEngine.UI;

public class PlayerUI : MonoBehaviour
{
    [SerializeField] private Text nameText;
    [SerializeField] private Slider healthSlider;

    private SoliderController target;
    // UI 在玩家位置的偏移
    private Vector3 screenOffset = new Vector3(0, 30, 0);
    float characterControllerHeight = 0;
    Transform targetTransform;
    Renderer targetRenderer;
    CanvasGroup canvasGroup;
    Vector3 targetPosition;

    private void Awake()
    {
        canvasGroup = GetComponent<CanvasGroup>();
        this.transform.SetParent(GameObject.Find("MapCanvas").GetComponent<Transform>(), false);
    }
    public void SetTarget(SoliderController target)
    {
        if (target != null && target.photonView.Owner != null)
        {
            this.target = target;
            targetTransform = this.target.GetComponent<Transform>();
            targetRenderer = this.target.GetComponent<Renderer>();
            CharacterController characterController = target.GetComponent<CharacterController>();
            if (characterController != null)
            {
                characterControllerHeight = characterController.height;
            }
            if (nameText != null)
            {
                // 显示名称
                nameText.text = target.photonView.Owner.NickName;
            }
        }
    }
    private void Update()
    {
        if (target == null)
        {
            Destroy(this.gameObject);
            return;
        }
        if (healthSlider != null)
        {
            healthSlider.value = target.health;
        }
    }
    private void LateUpdate()
    {
        if (targetRenderer != null)
        {
            this.canvasGroup.alpha = targetRenderer.isVisible ? 1 : 0;
        }

        if (targetTransform != null)
        {
            targetPosition = targetTransform.position;
            targetPosition.y += characterControllerHeight;
            // 计算后的位置经过相机转化为 UI 坐标系 再加上偏移
            this.transform.position = Camera.main.WorldToScreenPoint(targetPosition) + screenOffset;
        }
    }
}
